package com.gitee.wsl.coroutines.executor.runnable

import com.gitee.wsl.concurrent.api.RunnableWithResult
import com.gitee.wsl.concurrent.api.SuspendRunnableWithResult
import kotlinx.coroutines.sync.Semaphore

/**
 * LimitedRunnable is an open class that implements the Runnable interface. It is used to execute a task with limited concurrency using a Semaphore.
 * The class takes a Semaphore and a parent task as constructor parameters.
 *
 * @param semaphore The Semaphore to control the concurrency limit.
 * @param parentTask The parent task to be executed.
 */
open class LimitedRunnable<T>(
    protected val semaphore: Semaphore,
    protected val parentTask: RunnableWithResult<T>
) : SuspendRunnableWithResult<T> {
    override suspend fun run():T {
        semaphore.acquire()
        try {
            return parentTask.run()
        }finally {
            semaphore.release()
        }
    }
}